import axios, { AxiosInstance, AxiosResponse } from 'axios';

// 类型定义
export interface Metric {
  id: string;
  name: string;
  type: 'histogram' | 'enum' | 'ukm_event' | 'ukm_metric';
  component?: string;
  description?: string;
  summary?: string;
  units?: string;
  file_path: string;
  line_number?: number;
  owner_name?: string;
  analysis_status?: 'ANALYZED' | 'PENDING' | 'FAILED';
  analysis_progress?: number;
  team_name?: string;
  assignment_reason?: string;
  assigned_at?: string;
  analyzed_by?: string;
  analyzed_at?: string;
  analysis_notes?: string;
  created_at?: string;
  updated_at?: string;
}

// API基础配置 - 改为Python backend的8000端口
const API_BASE_URL = process.env.REACT_APP_API_URL || 'http://localhost:8000/api/v1';

// 创建axios实例
const apiClient: AxiosInstance = axios.create({
  baseURL: API_BASE_URL,
  timeout: 30000,
  headers: {
    'Content-Type': 'application/json',
  },
});

// 请求拦截器 - 添加认证token和调试日志
apiClient.interceptors.request.use(
  (config) => {
    // 添加调试日志
    console.log('🚀 [API] 发送请求:', {
      method: config.method?.toUpperCase(),
      url: config.url,
      baseURL: config.baseURL,
      fullURL: `${config.baseURL}${config.url}`,
      headers: {
        'Content-Type': config.headers['Content-Type'],
        'Authorization': config.headers.Authorization ? '[HIDDEN]' : undefined,
      },
      data: config.data,
    });

    const token = localStorage.getItem('token');
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }

    // 验证请求数据格式
    if (config.data && typeof config.data === 'object') {
      // 检查是否有undefined的值
      const undefinedKeys = Object.keys(config.data).filter(key => config.data[key] === undefined);
      if (undefinedKeys.length > 0) {
        console.warn('⚠️ [API] 发现undefined字段:', undefinedKeys);
        // 移除undefined字段
        undefinedKeys.forEach(key => {
          delete config.data[key];
        });
      }

      // 验证字符串字段不为空字符串
      const emptyStringKeys = Object.keys(config.data).filter(key =>
        typeof config.data[key] === 'string' && config.data[key].trim() === ''
      );
      if (emptyStringKeys.length > 0) {
        console.warn('⚠️ [API] 发现空字符串字段:', emptyStringKeys);
      }
    }

    return config;
  },
  (error) => {
    console.error('❌ [API] 请求拦截器错误:', error);
    return Promise.reject(error);
  }
);

// 响应拦截器 - 统一错误处理
apiClient.interceptors.response.use(
  (response: AxiosResponse) => {
    console.log('✅ [API] 收到响应:', {
      status: response.status,
      url: response.config.url,
      method: response.config.method?.toUpperCase(),
      data: response.data,
    });
    return response;
  },
  (error) => {
    console.error('❌ [API] 请求错误:', {
      status: error.response?.status,
      url: error.config?.url,
      method: error.config?.method?.toUpperCase(),
      data: error.config?.data,
      responseData: error.response?.data,
      message: error.message,
    });

    // 移除自动重定向到登录页面的逻辑，允许页面正常处理401错误
    if (error.response?.status === 401) {
      // Token过期或无效，清除本地存储的token
      localStorage.removeItem('token');
      localStorage.removeItem('user');
      console.log('🔓 [API] 已清除过期token');
      // 不再自动重定向到登录页面
      // window.location.href = '/login';
    }

    // 400错误的特殊处理
    if (error.response?.status === 400) {
      console.error('❌ [API] 400错误详情:', error.response?.data);
    }

    return Promise.reject(error);
  }
);

// API响应类型定义
export interface ApiResponse<T = any> {
  success: boolean;
  data: T;
  message?: string;
  error?: {
    code: string;
    message: string;
  };
}

// 分页响应类型定义
export interface PaginatedResponse<T = any> {
  success: boolean;
  data: T[];
  total: number;
  page: number;
  page_size: number;
  message?: string;
}

// 统计数据类型定义
export interface TelemetryStats {
  total_metrics: number;
  by_type: Record<string, number>;
  top_components: Record<string, number>;
  by_analysis_status: {
    analyzed: number;
    not_analyzed: number;
    needs_collection: number;
    not_needed: number;
  };
  unassigned: number;
}


// 认证相关API - 适配Python backend
export const authApi = {
  /**
   * 用户登录 - 环境感知认证
   */
  async login(credentials?: {
    username?: string;
    password?: string;
  }): Promise<ApiResponse<{
    success: boolean;
    user?: {
      user_id: string;
      email: string;
      name: string;
    };
    token?: string;
    message?: string;
  }>> {
    const response = await apiClient.post('/auth/login', credentials || {});
    return response.data;
  },

  /**
   * 获取当前用户信息 - 环境感知认证
   */
  async getCurrentUser(): Promise<ApiResponse<{
    success: boolean;
    user?: {
      user_id: string;
      email: string;
      name: string;
    };
    message?: string;
  }>> {
    const response = await apiClient.get('/auth/me');
    return response.data;
  },

  /**
   * 验证token
   */
  async validateToken(): Promise<ApiResponse<{
    success: boolean;
    user?: {
      user_id: string;
      email: string;
      name: string;
    };
    token?: string;
    message?: string;
  }>> {
    const response = await apiClient.post('/auth/validate');
    return response.data;
  },

  /**
   * 刷新token
   */
  async refreshToken(): Promise<ApiResponse<{
    success: boolean;
    user?: {
      user_id: string;
      email: string;
      name: string;
    };
    token?: string;
    message?: string;
  }>> {
    const response = await apiClient.post('/auth/refresh');
    return response.data;
  },
};

// 遥测点相关API - 适配Python backend
export const telemetryApi = {
  /**
   * 获取遥测点列表 - 从extractor数据库获取
   */
  async getTelemetryPoints(params: {
    page?: number;
    page_size?: number;
    type_filter?: 'histogram' | 'enum' | 'ukm_event' | 'ukm_metric' | 'UMA' | 'UKM';
    component_filter?: string;
    team_filter?: string;
    search?: string;
    directory?: string;
    directory_id?: number;
  } = {}): Promise<PaginatedResponse<{
      id: number;
      name: string;
      type: string;
      description?: string;
      units?: string;
      component?: string;
      file_path: string;
      line_number?: number;
      owner?: string;
      assigned_team_id?: string;
      assigned_team_name?: string;
      analysis_status: string;
      analysis_notes?: string;
      analyzed_by?: string;
      analyzed_at?: string;
      metadata?: Record<string, any>;
    }>> {
    const response = await apiClient.get('/', { params });
    return response.data;
  },

  /**
   * 获取遥测点详情
   */
  async getTelemetryPoint(telemetryId: number): Promise<{
    id: number;
    name: string;
    type: string;
    description?: string;
    units?: string;
    component?: string;
    file_path: string;
    line_number?: number;
    owner?: string;
    assigned_team_id?: string;
    assigned_team_name?: string;
    analysis_status: string;
    analysis_notes?: string;
    analyzed_by?: string;
    analyzed_at?: string;
    metadata?: Record<string, any>;
  }> {
    const response = await apiClient.get(`/${telemetryId}`);
    return response.data;
  },

  /**
   * 获取遥测点统计概览
   */
  async getTelemetryStats(params: {
    directory?: string;
  } = {}): Promise<ApiResponse<TelemetryStats>> {
    const response = await apiClient.get('/stats/overview', { params });
    // The API already returns the correct structure, just return it directly
    return response.data;
  },

  /**
   * 更新遥测点分析状态
   */
  async updateAnalysisStatus(telemetryId: number, data: {
    analysis_status: string;
    analysis_notes?: string;
    team_id?: string;
  }): Promise<ApiResponse<{
    success: boolean;
    message: string;
  }>> {
    const response = await apiClient.put(`/${telemetryId}/analysis`, data);
    return response.data;
  },

  /**
   * 批量更新遥测点分析状态
   */
  async batchUpdateAnalysisStatus(telemetryIds: number[], data: {
    analysis_status: string;
    analysis_notes?: string;
    team_id?: string;
  }): Promise<ApiResponse<{
    success: boolean;
    message: string;
  }>> {
    const response = await apiClient.put('/batch-analysis', {
      telemetry_ids: telemetryIds,
      ...data
    });
    return response.data;
  },
};

// 团队相关API - 适配Python backend
export const teamApi = {
  /**
   * 获取团队列表
   */
  async getTeams(params: {
    skip?: number;
    limit?: number;
  } = {}): Promise<Array<{
    id: string;
    name: string;
    description?: string;
    created_by: string;
    created_at: string;
    updated_at: string;
    member_count: number;
    assignment_count: number;
  }>> {
    const response = await apiClient.get('/teams/', { params });
    return response.data;
  },

  /**
   * 创建团队
   */
  async createTeam(data: {
    name: string;
    description?: string;
  }): Promise<{
    id: string;
    name: string;
    description?: string;
    created_by: string;
    created_at: string;
    updated_at: string;
    member_count: number;
    assignment_count: number;
  }> {
    const response = await apiClient.post('/teams/', data);
    return response.data;
  },

  /**
   * 获取团队详情
   */
  async getTeam(teamId: string): Promise<{
    id: string;
    name: string;
    description?: string;
    created_by: string;
    created_at: string;
    updated_at: string;
    member_count: number;
    assignment_count: number;
  }> {
    const response = await apiClient.get(`/teams/${teamId}`);
    return response.data;
  },

  /**
   * 更新团队信息
   */
  async updateTeam(teamId: string, data: {
    name?: string;
    description?: string;
  }): Promise<{
    id: string;
    name: string;
    description?: string;
    created_by: string;
    created_at: string;
    updated_at: string;
    member_count: number;
    assignment_count: number;
  }> {
    const response = await apiClient.put(`/teams/${teamId}`, data);
    return response.data;
  },

  /**
   * 删除团队
   */
  async deleteTeam(teamId: string): Promise<ApiResponse<{ message: string }>> {
    const response = await apiClient.delete(`/teams/${teamId}`);
    return response.data;
  },

  /**
   * 获取团队文件分配
   */
  async getTeamFileAssignments(teamId: string): Promise<Array<{
    id: string;
    team_id: string;
    file_pattern: string;
    description?: string;
    is_active: boolean;
    created_by: string;
    created_at: string;
    updated_at: string;
  }>> {
    const response = await apiClient.get(`/teams/${teamId}/assignments`);
    return response.data;
  },

  /**
   * 创建团队文件分配
   */
  async createTeamFileAssignment(teamId: string, data: {
    file_pattern: string;
    description?: string;
    is_active?: boolean;
  }): Promise<{
    id: string;
    team_id: string;
    file_pattern: string;
    description?: string;
    is_active: boolean;
    created_by: string;
    created_at: string;
    updated_at: string;
  }> {
    const response = await apiClient.post(`/teams/${teamId}/assignments`, data);
    return response.data;
  },

  /**
   * 获取团队成员列表
   */
  async getTeamMembers(teamId: string): Promise<Array<{
    id: string;
    team_id: string;
    user_id: string;
    role: string;
    status: string;
    joined_at: string;
    user: {
      id: string;
      name: string;
      email: string;
      avatar_url?: string;
    };
  }>> {
    const response = await apiClient.get(`/teams/${teamId}/members`);
    return response.data;
  },

  /**
   * 添加团队成员
   */
  async addTeamMember(teamId: string, data: {
    user_name: string;
    role: string;
  }): Promise<{
    id: string;
    team_id: string;
    user_id: string;
    role: string;
    status: string;
    joined_at: string;
    user: {
      id: string;
      name: string;
      email: string;
      avatar_url?: string;
    };
  }> {
    const response = await apiClient.post(`/teams/${teamId}/members`, data);
    return response.data;
  },

  /**
   * 更新团队成员角色
   */
  async updateTeamMemberRole(teamId: string, userId: string, role: string): Promise<{
    id: string;
    team_id: string;
    user_id: string;
    role: string;
    status: string;
    joined_at: string;
    user: {
      id: string;
      name: string;
      email: string;
      avatar_url?: string;
    };
  }> {
    const response = await apiClient.put(`/teams/${teamId}/members/${userId}`, { role });
    return response.data;
  },

  /**
   * 移除团队成员
   */
  async removeTeamMember(teamId: string, userId: string): Promise<ApiResponse<{ message: string }>> {
    const response = await apiClient.delete(`/teams/${teamId}/members/${userId}`);
    return response.data;
  },
};

// 邀请相关API - Python Backend简化团队管理，暂时移除邀请功能
export const invitationApi = {
  // 简化版本，暂时不支持邀请功能
  async getInvitationByToken(): Promise<ApiResponse<{ message: string }>> {
    return Promise.resolve({
      success: false,
      data: { message: 'Invitation functionality is currently being refactored.' },
      error: {
        code: 'FEATURE_NOT_AVAILABLE',
        message: 'Invitation functionality is currently being refactored.'
      }
    } as any);
  },
};

// 分析相关API - Python Backend已集成分析功能到遥测点API，保持兼容性
export const analysisApi = {
  /**
   * 获取分析统计 - 重定向到遥测点API
   */
  async getAnalysisStats(): Promise<ApiResponse<TelemetryStats>> {
    // 重定向到遥测点统计API
    const response = await telemetryApi.getTelemetryStats();
    return response;
  },

  /**
   * 获取团队分析统计
   */
  async getTeamAnalysisStats(): Promise<ApiResponse<Array<{
    teamId: string;
    teamName: string;
    totalPoints: number;
    analyzedPoints: number;
    analysisProgress: number;
  }>>> {
    const response = await apiClient.get('/stats/teams');
    return response.data;
  },

  /**
   * 获取团队列表 - 重定向到团队API
   */
  async getTeams(): Promise<Array<{
    id: string;
    name: string;
    description?: string;
    member_count: number;
    assignment_count: number;
  }>> {
    // 重定向到团队API
    const response = await teamApi.getTeams();
    return response;
  },

  /**
   * 获取遥测点详情 - 重定向到遥测点API
   */
  async getTelemetryPoint(pointId: number): Promise<{
    id: number;
    name: string;
    type: string;
    description?: string;
    units?: string;
    component?: string;
    file_path: string;
    line_number?: number;
    owner?: string;
    assigned_team_id?: string;
    assigned_team_name?: string;
    analysis_status: string;
    analysis_notes?: string;
    analyzed_by?: string;
    analyzed_at?: string;
    metadata?: Record<string, any>;
    tokens?: Array<{
      token_key: string;
      token_name: string;
    }>;
    enum_values?: string[];
  }> {
    // 重定向到遥测点详情API
    const response = await telemetryApi.getTelemetryPoint(pointId);
    return response;
  },

  /**
   * 获取遥测点列表 - 重定向到遥测点API
   */
  async getTelemetryPoints(params: {
    page?: number;
    page_size?: number;
    type_filter?: 'histogram' | 'enum' | 'ukm_event' | 'ukm_metric' | 'UMA' | 'UKM';
    component_filter?: string;
    team_filter?: string;
    search?: string;
    directory?: string;
    directory_id?: number;
  } = {}): Promise<PaginatedResponse<{
      id: number;
      name: string;
      type: string;
      description?: string;
      units?: string;
      component?: string;
      file_path: string;
      line_number?: number;
      owner?: string;
      assigned_team_id?: string;
      assigned_team_name?: string;
      analysis_status: string;
      analysis_notes?: string;
      analyzed_by?: string;
      analyzed_at?: string;
      metadata?: Record<string, any>;
    }>> {
    // 重定向到遥测点列表API
    const response = await telemetryApi.getTelemetryPoints(params);
    return response;
  },

  /**
   * 更新分析状态 - 重定向到遥测点API
   */
  async updateAnalysisStatus(telemetryId: number, data: {
    analysis_status: string;
    analysis_notes?: string;
    team_id?: string;
  }): Promise<ApiResponse<{
    success: boolean;
    message: string;
  }>> {
    // 重定向到遥测点分析状态更新API
    const response = await telemetryApi.updateAnalysisStatus(telemetryId, data);
    return response;
  },

  /**
   * 批量更新分析状态 - 重定向到遥测点API
   */
  async batchUpdateAnalysisStatus(telemetryIds: number[], data: {
    analysis_status: string;
    analysis_notes?: string;
    team_id?: string;
  }): Promise<ApiResponse<{
    success: boolean;
    message: string;
  }>> {
    // 重定向到遥测点批量分析状态更新API
    const response = await telemetryApi.batchUpdateAnalysisStatus(telemetryIds, data);
    return response;
  },
};

// 目录树相关API - 新的后端API
export const directoryApi = {
  /**
   * 获取目录树结构
   */
  async getDirectoryTree(params: {
    root_path?: string;
    max_depth?: number;
    include_metrics?: boolean;
    team_filter?: string;
    component_filter?: string;
    type_filter?: 'histogram' | 'enum' | 'ukm_event' | 'ukm_metric' | 'UMA' | 'UKM';
  } = {}): Promise<{
    success: boolean;
    data: any;
    stats: {
      total_directories: number;
      total_files: number;
      total_metrics: number;
      deepest_depth: number;
      metric_types: Record<string, number>;
      analysis_stats: Record<string, number>;
      unique_teams: number;
      unique_components: number;
      root_nodes_count: number;
    };
    root_path: string;
    total_metrics: number;
    filters_applied: {
      team_filter?: string;
      component_filter?: string;
      type_filter?: string;
    };
  }> {
    const response = await apiClient.get('/directory/directory-tree', { params });
    return response.data;
  },

  /**
   * 获取目录统计概览
   */
  async getDirectoryStats(params: {
    team_filter?: string;
    component_filter?: string;
    type_filter?: 'histogram' | 'enum' | 'ukm_event' | 'ukm_metric' | 'UMA' | 'UKM';
  } = {}): Promise<{
    total_directories: number;
    total_files: number;
    total_metrics: number;
    deepest_depth: number;
    metric_types: Record<string, number>;
    analysis_stats: Record<string, number>;
    unique_teams: number;
    unique_components: number;
    root_nodes_count: number;
  }> {
    const response = await apiClient.get('/directory/directory-stats', { params });
    return response.data;
  },

  /**
   * 获取目录列表（带统计信息）
   */
  async getDirectoryList(params: {
    page?: number;
    page_size?: number;
    search?: string;
    sort_by?: string;
    sort_order?: string;
    min_metrics?: number;
    team_filter?: string;
  } = {}): Promise<{
    success: boolean;
    data: Array<{
      id: number;
      name: string;
      path: string;
      metric_count: number;
      created_at: string;
      updated_at: string;
      team_id?: string;
      team_name?: string;
      assignment_confidence?: number;
      assignment_method?: string;
      assigned_at?: string;
    }>;
    total_count: number;
    execution_time_ms: number;
    timestamp: string;
  }> {
    // Transform parameters to match backend expectations
    const apiParams = {
      limit: params.page_size,
      offset: params.page && params.page_size ? (params.page - 1) * params.page_size : 0,
      search: params.search,
      sort_by: params.sort_by || 'metric_count',
      order: params.sort_order?.toUpperCase() || 'DESC',
      team_filter: params.team_filter,
    };

    const response = await apiClient.get('/directories/list', { params: apiParams });
    return response.data;
  },

  /**
   * 批量更新目录下遥测点的团队
   */
  async batchUpdateMetricsTeam(data: {
    directory_path: string;
    team_name: string;
    analysis_notes?: string;
  }): Promise<{
    success: boolean;
    message: string;
    updated_count: number;
  }> {
    const response = await apiClient.post('/directory/batch-update-metrics-team', data);
    return response.data;
  },

  /**
   * 获取目录团队分布详情
   */
  async getDirectoryTeamDistribution(directoryId: number): Promise<{
    success: boolean;
    data: {
      directory_path: string;
      directory_name: string;
      total_metrics: number;
      teams: Array<{
        team_name: string;
        total_count: number;
        uma_metrics: number;
        ukm_metrics: number;
        metric_types: {
          histogram: number;
          enum: number;
          ukm_event: number;
          ukm_metric: number;
          unknown: number;
        };
        assignment_confidence: number;
        last_assigned: string | null;
      }>;
      unassigned_count: number;
      uma_summary: {
        total: number;
        teams: Record<string, number>;
      };
      ukm_summary: {
        total: number;
        teams: Record<string, number>;
      };
    };
  }> {
    const response = await apiClient.get(`/directory/${directoryId}/team-distribution`);
    return response.data;
  },

  /**
   * 批量分析目录下的遥测点
   */
  async batchAnalyzeMetrics(data: {
    directory_path: string;
    should_collect: boolean;
    analysis_reason: string;
  }): Promise<{
    success: boolean;
    message: string;
    analysis_task_id?: string;
    queued_count: number;
  }> {
    const response = await apiClient.post('/directory/batch-analyze-metrics', data);
    return response.data;
  },
  };

// 搜索相关API - 适配Python backend
export const searchApi = {
  /**
   * 高级搜索
   */
  async search(data: {
    query: string;
    filters?: Record<string, any>;
    include_ukm?: boolean;
    include_uma?: boolean;
    include_enums?: boolean;
    team_filter?: string;
    component_filter?: string;
  }, params: {
    page?: number;
    page_size?: number;
  } = {}): Promise<ApiResponse<{
    success: boolean;
    data: Array<{
      id: number;
      name: string;
      type: string;
      description?: string;
      units?: string;
      component?: string;
      file_path: string;
      line_number?: number;
      owner?: string;
      assigned_team_id?: string;
      assigned_team_name?: string;
      match_score: number;
      match_fields: Array<string>;
    }>;
    total: number;
    query: string;
    page: number;
    page_size: number;
    message?: string;
  }>> {
    const response = await apiClient.post('/', data, { params });
    return response.data;
  },

  /**
   * 获取搜索建议
   */
  async getSuggestions(params: {
    q: string;
    limit?: number;
  }): Promise<ApiResponse<{
    success: boolean;
    suggestions: Array<string>;
    message?: string;
  }>> {
    const response = await apiClient.get('/suggestions', { params });
    return response.data;
  },

  /**
   * 获取组件列表
   */
  async getComponents(params: {
    limit?: number;
  } = {}): Promise<Array<string>> {
    const response = await apiClient.get('/components', { params });
    return response.data;
  },

  /**
   * 获取Tokens列表
   */
  async getTokens(params: {
    limit?: number;
  } = {}): Promise<Array<string>> {
    const response = await apiClient.get('/tokens', { params });
    return response.data;
  },
};

// 默认导出apiClient，用于自定义API调用
export default apiClient;